package wangjg.security.resource.factory.xml2;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import wangjg.security.core.ResourceFactory;
import wangjg.security.resource.factory.xml2.entity.Resource;

/**
 * 从xml文件加载配置(工具类)实现ResourceFactory
 * @author wangjg
 *
 */
public class XmlResourceFactory implements ResourceFactory{
	private Set<Resource> resources;
	private String path;
	
	@Override
	public Iterator<Resource> iterator() {
		return this.load().iterator();
	}

	public Set<Resource> load() {
		if(this.resources!=null){
			return this.resources;
		}
		return this._load();
	}
	
	private synchronized Set<Resource> _load() {
		if(this.resources!=null){
			return this.resources;
		}
		this.resources=new LinkedHashSet<Resource>();
		InputStream is = null;
		try {
			is = this.getClass().getResourceAsStream(path);
			SAXReader xreader = new SAXReader();
			Document document = xreader.read(is);

			this.__loadSimpleHttpResources(document);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}finally{
			try {
				if(is!=null)is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return this.resources;
	}

	/*
	 * handle <url/>标签
	 */
	private void __loadSimpleHttpResources(Document document) {
		Element root = document.getRootElement();
		List<?> list = root.selectNodes("/resources/url");
        for(Object node: list){
            Element e = (Element) node;
            Resource httpResource=this.___createSimpleHttpResource(e);
            this.resources.add(httpResource);
        }
	}

	private Resource ___createSimpleHttpResource(Element e){
        String pattern = e.attributeValue("pattern");
        Resource resource = new Resource();
        resource.setPattern(pattern);
        String[] roles = e.getTextTrim().split(",");
        for(String role : roles){
        	resource.getAuthorities().add(role);
        }
        return resource;
	}
}
